package com.ccsoft.netty.heartbeat.client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * @author chanchaw
 * @create 2022-07-20 14:26
 */
public class ClientInitializer extends ChannelInitializer<SocketChannel> {

    private HeartbeatClient client;
    public ClientInitializer(HeartbeatClient heartbeatClient) {
        if(heartbeatClient == null) System.out.println("客户端不可为空！");
        client = heartbeatClient;
    }
//    private ReconnectHandler reconnectHandler;
//    private EchoHandler echoHandler;


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pl = ch.pipeline();
        // 管道内的第一个 handler 是重连策略 - 即打开客户端则判断是否连接进行重连
        pl.addLast(new ReconnectHandler(client));
        pl.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
        pl.addLast(new LengthFieldPrepender(4));
        pl.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pl.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pl.addLast(new ClientHandler());
    }
}
